package com.szeldon.declatest.exec.plugins.jms;

import java.util.logging.Logger;

import org.apache.activemq.broker.BrokerService;
import org.testng.ITestContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.xml.XmlTest;

/**
 * Configurator for tests of JMS executor plugin.
 * 
 * @author szeldon
 * 
 */
public class JmsTestsConfigurator {

    public static final String JMS_BIND_ADDRESS_PARAMETER = "jms.bindAddress";
    public static final String JMS_BROKER_NAME_PARAMETER = "jms.brokerName";
    public static final String CONTEXT_ATTRIBUTE_NAME_FOR_JMS_SERVER = "jms.server";

    private static Logger logger = Logger.getLogger(JmsTestsConfigurator.class.getName());

    private BrokerService brokerService;

    @BeforeTest
    public void startJmsServer(ITestContext testContext) throws Exception {
        XmlTest xmlTest = testContext.getCurrentXmlTest();
        String bindAddress = xmlTest.getParameter(JMS_BIND_ADDRESS_PARAMETER);
        String brokerName = xmlTest.getParameter(JMS_BROKER_NAME_PARAMETER);

        if (bindAddress == null || brokerName == null) {
            throw new IllegalArgumentException("Not enough parameters. (bindAddress=" + bindAddress + "; brokerName="
                    + brokerName + ")");
        }

        logger.info("Starting JMS server (bindAddress=" + bindAddress + "; brokerName=" + brokerName
                + ") for Declatest tests.");
        brokerService = new BrokerService();
        brokerService.addConnector(bindAddress);
        brokerService.setBrokerName(brokerName);
        brokerService.setPersistent(false);
        brokerService.setUseJmx(true);
        brokerService.start();
        logger.info("JMS server for Declatest tests started.");

        // adding JMS broker service to test context so that it will be available to tests inside the same <test> tag
        testContext.setAttribute(CONTEXT_ATTRIBUTE_NAME_FOR_JMS_SERVER, brokerService);
    }

    @AfterTest
    public void stopJmsServer() throws Exception {
        logger.info("Stopping JMS server for Declatest tests.");
        brokerService.stop();
        logger.info("JMS server for Declatest tests stopped.");
    }
}
